package org.zkMock;

import java.util.ArrayList;

@SuppressWarnings("all")
public class ZkWatchMock {

    private static ArrayList<String> list = new ArrayList();

    public static void main(String[] args) throws Exception {

        new Thread(new Runnable() {
            boolean flag = true;
            String latestEle = null;
            /**
             * 如果变量listSize前加上volatile,线程zkMonitor就不会"卡住",System.out.println("进入if了");会执行
             * 如果变量listSize取消volatile,线程zkMonitor就会"卡住",System.out.println("进入if了");不会执行
             */
            volatile int listSize;

            public void run() {
                System.out.println("zk监控线程执行了");

                while (flag) {
                    if (getListSize() != 0) {
                        System.out.println("进入if了");
                        latestEle =list.get(list.size() - 1);
                        try {
                            Thread.sleep(1000L);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }

                        System.out.println("获取到最后元素是:" + this.latestEle);
                        System.out.println();
                    }
                }

            }

            public int getListSize() {
                listSize = list.size();
                return listSize;
            }
        },"zkWatcher").start();


        Thread.sleep(10L);

        list.add("aa");
        list.add("bb");
        System.out.println("主线程执行完成-----打印list:" + list);
    }
}